package org.yw.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created By YU WEI on 2020.09.07
 */
@Component
public class RedisUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置key
     * @param key
     * @param value
     */
    public void setKey(String key,String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }

    /**
     * 获取value
     * @param key
     * @return
     */
    public String getValue(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 判断键存在
     * @param key
     * @return
     */
    public boolean isExists(String key){
        return stringRedisTemplate.hasKey(key);
    }

    /**
     * 设置有限时间
     * @param key
     * @param time
     */
    public void expire(String key,long time){
        stringRedisTemplate.expire(key,time,TimeUnit.SECONDS);
    }

    /**
     * 设置锁
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean Lock(String key,String value,long time){
        return stringRedisTemplate.opsForValue().setIfAbsent(key,value,time, TimeUnit.SECONDS);
    }

    /**
     * 解锁
     * @param key
     */
    public void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    public long getTime(String key){
        return    stringRedisTemplate.getExpire(key,TimeUnit.SECONDS);
    }
}
